package ltd.hyangyang.rpc.core.remoting.client;

import io.netty.channel.*;
import ltd.hyangyang.rpc.common.bean.Response;
import ltd.hyangyang.rpc.common.exception.RpcException;
import ltd.hyangyang.rpc.common.utils.SingletonFactory;
import ltd.hyangyang.rpc.core.remoting.CustomHandler;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

public class RpcClientHandler extends CustomHandler {

    ConcurrentHashMap<String, CompletableFuture<Response>> progressFutureTask ;
    public RpcClientHandler(){
        progressFutureTask = UnfinishChannel.progressFutureTask;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //服务端返回的消息
        Response response = (Response) msg;
        CompletableFuture<Response> completableFuture = progressFutureTask.get(response.getRequestId());
        completableFuture.complete(response);
        progressFutureTask.remove(response);
    }

    @Override
    public void handlerAllIdle(Channel channel) {
        //实现调用一个接口，实现心跳机制
        RpcClientNetty rpcClientNetty = SingletonFactory.checkSingletonExist(RpcClientNetty.class);

        rpcClientNetty.sendPing(channel);
    }
}
